from PyQt4.QtCore import *
from PyQt4.QtGui import *

import math
import graph
import ops
import sys

import ErrorItem

class modelScene(QGraphicsScene):
    def __init__(self):
        QGraphicsScene.__init__(self)
        self.graph = graph.digraph()
        self.undoStack = QUndoStack(self)
        self.errors=[]

    def addOperatorItem(self,item):
        command = ops.CommandAddOperatorItem(self,item)
        self.undoStack.push(command)
        #self.addItem(item)
        #self.graph.add_graph(item.graph)
        
    def wheelEvent(self,event):
        nd = float(event.delta())/100.0
        z=math.pow(0.9,float(nd))
        self.views()[0].scale(z,z)
        event.accept()

    def dumpGraph(self):
        for n in self.graph.nodes():
            print n,
            print self.graph.incidents(n)

    def dumpSort(self):
        print self.graph.topological_sorting()

    def has_cycle(self):
        if self.graph.find_cycle():
            print "graph has cycle"
            return True
        print "No Cycles"
        return False

    def clearErrors(self):
        for e in self.errors:
            e.deleteLater()
        self.errors=[]

    def addError(self,item,error):
        self.errors.append(ErrorItem.ErrorItem(item,error,self))
    
    def run_process(self):
        nodes = self.graph.topological_sorting()
        
        for n in nodes:
            try:
                n.process()
            except:
                error = sys.exc_info()[0]
                self.addError(n,error)

#        for n in nodes:
#            try:
#                n.process()
#            except:
#                print "process exception"
#                print n.pos()

class Item(QAbstractGraphicsShapeItem):
    def __init__(self):
        QGraphicsItem.__init__(self)

